<svelte:head>
    <title>{pageTitle} | Datawrapper</title>
</svelte:head>

<div class="row" style="">
    <div class="span12 admin">
        <h1 class="title" style="margin-bottom: 18px">{title}</h1>
    </div>
</div>

<div class="settings-section dw-create-visualize chart-editor chart-editor-web admin">
    <div class="visconfig">
        <NavTabs basePath="team/{team.id}" ref:navTabs groups="{groups}" bind:activeTab>
            <div slot="aboveContent">
                {#if activeTab && activeTab.h1 }
                <h2>{ @html activeTab.h1 }</h2>
                {/if} {#if error}
                <div class="alert alert-danger">{error}</div>
                {/if}
            </div>
            <div slot="belowMenu">
                <hr />
                <ul class="unstyled">
                    <li>
                        <a href="/account/teams"
                            ><i class="fa fa-fw fa-arrow-left"></i> {__('account / my-teams')}</a
                        >
                    </li>
                    <li>
                        <a href="/team/{team.id}"
                            ><i class="fa fa-fw fa-arrow-left"></i> {__('nav / team / charts')}</a
                        >
                    </li>
                </ul>
            </div>
        </NavTabs>
    </div>
</div>

<script>
    import { __ } from '@datawrapper/shared/l10n';
    import truncate from '@datawrapper/shared/truncate';
    import NavTabs from '../shared/NavTabs.html';
    import Members from './tabs/Members.html';
    import Settings from './tabs/Settings.html';
    import DeleteTeam from './tabs/DeleteTeam.html';
    import ProductTable from './tabs/ProductTable.html';
    import storeTeamSettings from './storeTeamSettings';

    const SettingsTab = {
        id: 'settings',
        title: __('teams / tab / settings'),
        icon: 'fa fa-gears',
        group: __('teams / group / users'),
        order: 10,
        h1: __('teams / defaults / h1'),
        ui: Settings,
        data: {}
    };

    const MembersTab = {
        id: 'members',
        title: __('teams / tab / members'),
        icon: 'im im-users',
        group: __('teams / group / users'),
        order: 20,
        h1: __('teams / h1'),
        ui: Members
    };

    let app;
    let popstate = false;

    export default {
        components: {
            NavTabs
        },
        data() {
            return {
                allTabs: [
                    SettingsTab,
                    MembersTab,
                    {
                        id: 'delete',
                        title: __('teams / tab / deleteTeam'),
                        icon: 'fa fa-times',
                        group: __('teams / group / advanced'),
                        order: 80,
                        h1: __('teams / delete / h1'),
                        ui: DeleteTeam,
                        ownerOnly: true
                    },
                    {
                        id: 'products',
                        title: __('teams / tab / adminProducts'),
                        icon: 'fa fa-list-alt',
                        group: __('teams / group / internal'),
                        order: 90,
                        h1: __('teams / products / h1'),
                        ui: ProductTable,
                        adminOnly: true
                    }
                ],
                pluginTabs: [],
                activeTab: null,
                ui: Settings,
                team: {
                    name: ''
                },
                settings: {},
                users: [],
                userId: null,
                visualizations: [],
                visualizationsArchive: [],
                error: null
            };
        },
        computed: {
            pageTitle({ team, activeTab }) {
                return `${activeTab ? activeTab.h1 : ''} | ${truncate(team.name, 17, 8)}`;
            },
            title({ team }) {
                return `${truncate(team.name, 17, 8)} » ${__('nav / team / settings')}`;
            },
            tabs({ allTabs, team, pluginTabs, isAdmin, $role }) {
                const tabs = [].concat(allTabs, pluginTabs);

                return tabs
                    .filter(tab => {
                        if (tab.adminOnly && !isAdmin) return false;
                        if (tab.ownerOnly && !(isAdmin || $role === 'owner')) return false;
                        return true;
                    })
                    .map(tab => ({ ...tab, h1: tab.h1.replace('%team%', team.name) }));
            },
            groups({
                tabs,
                isAdmin,
                team,
                users,
                userId,
                settings,
                defaultTheme,
                hasThemeWithLogo,
                themes,
                folders,
                locales,
                visualizations,
                visualizationsArchive
            }) {
                const groups = [];

                function get(groups, groupId) {
                    const g = groups.filter(el => el.title === groupId);
                    if (g.length) return g[0];

                    groups.push({
                        title: groupId,
                        tabs: []
                    });

                    return groups[groups.length - 1];
                }

                tabs.forEach(tab => {
                    tab.data = {
                        isAdmin,
                        team,
                        users,
                        userId,
                        settings,
                        defaultTheme,
                        hasThemeWithLogo,
                        themes,
                        folders,
                        locales,
                        visualizations,
                        visualizationsArchive,
                        ...tab.data
                    };
                    tab.onchange = (data, tabApp) => {
                        app.onTabChange(data, tabApp);
                    };
                    get(groups, tab.group).tabs.push(tab);
                });

                groups.forEach(group => {
                    group.tabs.sort((a, b) => a.order - b.order);
                });

                return groups;
            }
        },
        helpers: { __ },
        methods: {
            onTabChange({ team, settings, defaultTheme }, tab) {
                this.set({ error: null });
                storeTeamSettings(team, settings, defaultTheme)
                    .then(() => {
                        this.set({
                            team,
                            settings,
                            defaultTheme
                        });
                        if (tab && tab.saved) {
                            tab.saved();
                        }
                    })
                    .catch(e => {
                        this.set({ error: __('teams / error', 'core', e.message) });
                        console.error(e);
                    });
            },
            setTab(id) {
                const { groups } = this.get();
                let foundTab = false;
                groups.forEach(group => {
                    group.tabs.forEach(tab => {
                        if (tab.id === id) {
                            this.refs.navTabs.activateTab(tab);
                            foundTab = true;
                        }
                    });
                });

                if (!foundTab) {
                    this.set({
                        activeTab: SettingsTab
                    });
                }
            }
        },
        oncreate() {
            app = this;
            const path = window.location.pathname.split('/').slice(-1);
            const initialTab = path[0] || 'settings';
            this.setTab(initialTab);

            window.addEventListener('popstate', ({ state }) => {
                popstate = true;
                setTimeout(() => (popstate = false), 100);
                this.setTab(state.id);
            });
        },
        onstate({ changed, current }) {
            if (changed.activeTab && current.activeTab && !popstate) {
                window.history.pushState(
                    { id: current.activeTab.id },
                    '',
                    `/team/${current.team.id}/${current.activeTab.id}`
                );
            }
        }
    };
</script>

<style lang="less">
    .settings-section {
        padding-top: 10px;
        margin-top: 10px;

        .base-dropdown-content {
            top: 30px !important;
        }
    }

    .group {
        text-transform: uppercase;
        padding: 8px;
        font-weight: bold;
        font-size: 12px;
    }
    li.active a {
        background: #18a1cd;
        border-color: #18a1cd;
        color: #fff;
        font-weight: bold;
    }
    .span2 .nav a i {
        width: 15px;
    }

    .settings-section {
        :global(p.help) {
            font-size: 14px;
            color: #777;
            line-height: 1.5;
        }
    }

    .admin h2 {
        font-size: 26px;
        border-bottom: 1px solid #eee;
        margin-bottom: 1em;
        padding-bottom: 1ex;
    }

    .admin :global(h3) {
        font-size: 22px;
    }
    :global(.control-group) {
        position: relative;
    }
    ul.unstyled li {
        margin-bottom: 8px;
    }
</style>
